<?php
namespace Admin\Controller;

use Util\AccessController;

class CouponController extends AccessController {

    public function Index() {
        $LS = Service('Card', 'card');
        $DATA = $LS->query(array('STATE' => 2));
        foreach ($DATA as $k => $v) {
            $DATA[$k]['STATES'] = '正在进行';
            $DATA[$k]['url'] = 'http://www.yanxiang.pw/Book/index.php/Coupon/Share?ID='.passport_encrypt($v['ID'],C('JM_KEY'));
            if ($v['ETIME'] < date('Y-m-d')) {
                $DATA[$k]['STATES'] = '过期了';
                $DATA[$k]['url'] = '';
            }
            if ($v['STIME'] > date('Y-m-d')) {
                $DATA[$k]['STATES'] = '还没开始';
                $DATA[$k]['url'] = '';
            }
        }

        $this->DATA = $DATA;
        $this->display();
    }

    public function Add() {
        if ($_POST['ETIME'] >= $_POST['STIME']) {
            $LS = Service('Card', 'card');
            $save = $_POST;
            $save['STATE'] = 2;
            $OK = $LS->insert($save);
            $OK ? $this->success('添加成功') : $this->error('添加失败');
        } else {
            $this->error('设置时间有误');
        }

    }

    public function Card_log_Index() {
        $LS = Service('Card', 'card_log');
        $files = 'ts_card.*,ts_card.NAME as card_name,ts_u_user.user_wx_name as wx_name ,ts_card_log.*';
        $DATA = $LS->query(array('ts_card.STATE' => 2), null,$files , null, 'ts_card on ts_card.ID = ts_card_log.CARD_ID', 'ts_u_user on ts_u_user.user_id = ts_card_log.USER_ID');
        $this->DATA = $DATA;

        //所有用户
        $LS1 = Service('Card','u_user');
        $user_date = $LS1->query();
        $this->USER_DATA = $user_date;

        //所有有效优惠劵
        $where['STATE']= 2;
        $where['ETIME'] =  array('GT',date('Y-m-d'));
        $LS2 = Service('Card','card');
        $coupon_data = $LS2->query($where);
        $this->COUPON_DATA =$coupon_data;
        $this->display();
    }
    /*
     * 给用户添加优惠劵
     * 并发送通知
     */
    public function AddCouponLog(){
        $save = $_POST;
        $save['CREATE_TIME']  = date('Y-m-d H:i:s');
        $save['CREATE_IP']  = get_client_ip();
        $LS = Service('Card','card_log');
        $OK = $LS->insert($save);

        if($OK){
            //优惠劵信息
            $LS1 = Service('Card','card');
            $cardData =$LS1->find(array('ID'=>$_POST['CARD_ID']));
            //用户信息
            $LS2 = Service('Card','u_user');
            $UserData =$LS2->find(array('user_id'=>$_POST['USER_ID']));
            $SendMsg = A('WxSendMsg');
            $SOK = $SendMsg->YHJ_SendMsg($UserData['user_wx'],$cardData['NAME']);
            if($SOK == 0){
                if($_POST['TYPE'] ==1){
                    echo 1;
                }else{
                    $this->success('添加成功') ;
                }
            }else{
                $this->error('通知失败');
            }
        }else{
            $this->error('添加失败');
        }

    }
}